"""
资源管理器

提供统一的资源清理机制，确保在程序退出时正确关闭所有文件句柄
"""

import atexit
import logging
import threading
from typing import List, Optional
import weakref

class ResourceManager:
    """资源管理器
    
    管理所有日志处理器的生命周期，确保程序退出时正确清理资源
    """
    
    def __init__(self):
        self._handlers: List[weakref.ref] = []
        self._lock = threading.Lock()
        self._cleanup_registered = False
        
    def register_handler(self, handler: logging.Handler) -> None:
        """注册日志处理器
        
        Args:
            handler: 要注册的日志处理器
        """
        with self._lock:
            self._handlers.append(weakref.ref(handler))
            if not self._cleanup_registered:
                atexit.register(self._cleanup_all)
                self._cleanup_registered = True
    
    def unregister_handler(self, handler: logging.Handler) -> None:
        """注销日志处理器
        
        Args:
            handler: 要注销的日志处理器
        """
        with self._lock:
            self._handlers = [ref for ref in self._handlers 
                            if ref() is not None and ref() is not handler]
    
    def _cleanup_all(self) -> None:
        """清理所有注册的处理器
        
        在程序退出时调用，确保所有文件句柄都被正确关闭
        """
        with self._lock:
            # 收集所有活动的处理器
            active_handlers = []
            for ref in self._handlers:
                handler = ref()
                if handler is not None:
                    active_handlers.append(handler)
            
            # 关闭所有处理器
            for handler in active_handlers:
                try:
                    handler.flush()
                    handler.close()
                except Exception:
                    # 忽略关闭过程中的错误
                    pass
            
            # 清空处理器列表
            self._handlers.clear()
    
    def close_logger_handlers(self, logger_name: str) -> None:
        """关闭指定logger的所有处理器
        
        Args:
            logger_name: logger的名称
        """
        try:
            logger = logging.getLogger(logger_name)
            for handler in logger.handlers[:]:
                try:
                    handler.flush()
                    handler.close()
                    logger.removeHandler(handler)
                except Exception:
                    pass
        except Exception:
            pass

# 全局资源管理器实例
resource_manager = ResourceManager()